//
// Created by alexander on 12/28/18.
//
#include <stdio.h>
#include <stdbool.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include </home/alexander/CLionProjects/FFmpegLogTest/log/log.h>
#include </home/alexander/CLionProjects/FFmpegLogTest/util/util.h>
#include </home/alexander/CLionProjects/FFmpegLogTest/extra_video.h>

/**调用函数处理 av_bitstream_filter_filter*/

int extraVideo(const char *srcFileName, const char *destFileName)
{
    int returnCode;
    AVFormatContext *avFormatContext = NULL;
    int videoStreamIndex = -1;
    AVPacket avPacket;
    AVBitStreamFilterContext * avBitStreamFilterContext = av_bitstream_filter_init("h264_mp4toannexb");
    FILE *destOutputFile = NULL;

    setLogLevel(AV_LOG_DEBUG);

    av_register_all();

    returnCode = avformat_open_input(&avFormatContext, srcFileName, NULL, NULL);
    if(returnCode < 0)
    {
        logError("Open input file error, code is %d\n", (int *) returnCode);
        goto __faile;
    }

    av_dump_format(avFormatContext, 0, srcFileName, 0);

    videoStreamIndex = av_find_best_stream(avFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if(videoStreamIndex < 0)
    {
        logError("Could not find video stream in input file %s\n", srcFileName);
        goto __faile;
    }

    destOutputFile = fopen(destFileName, "ab");
    if(destOutputFile == NULL)
    {
        logError("Open destOutputFile error, code is %d\n", (int *) returnCode);
        goto __faile;
    }

    av_init_packet(&avPacket);
    while(av_read_frame(avFormatContext, &avPacket) >= 0)
    {
        if(avPacket.stream_index == videoStreamIndex)
        {
            av_bitstream_filter_filter(avBitStreamFilterContext, avFormatContext->streams[videoStreamIndex]->codec, NULL, &avPacket.data, &avPacket.size, avPacket.data, avPacket.size, 0);
            fwrite(avPacket.data, 1, avPacket.size, destOutputFile);
        }
        av_packet_unref(&avPacket);
    }

__faile:
    avformat_close_input(&avFormatContext);
    av_bitstream_filter_close(avBitStreamFilterContext);
    fclose(destOutputFile);
    return returnCode;
}







































